package com.jet.rtdb.socket.server;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jet.rtdb.common.utils.MessageConstant;
import com.jet.rtdb.pojo.QueryHistoryDataList;
import com.jet.rtdb.pojo.QueryLastDataList;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @Author: zhangkaifeng.
 * @CreateTime: 2017/8/18 13:27
 * @Description:
 */


public class MessageServerDecoder extends LengthFieldBasedFrameDecoder {

    private GsonBuilder gsonbuilder = new GsonBuilder().serializeNulls();
    private Gson gson = gsonbuilder.create();
    private static final Logger logger = LoggerFactory.getLogger(MessageServerDecoder.class);

    /**
     * @param maxFrameLength      解码时，处理每个帧数据的最大长度
     * @param lengthFieldOffset   该帧数据中，存放该帧数据的长度的数据的起始位置
     * @param lengthFieldLength   记录该帧数据长度的字段本身的长度
     * @param lengthAdjustment    修改帧数据长度字段中定义的值，可以为负数
     * @param initialBytesToStrip 解析的时候需要跳过的字节数
     * @param failFast            为true，当frame长度超过maxFrameLength时立即报TooLongFrameException异常，为false，读取完整个帧再报异常
     */
    public MessageServerDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength,
                                int lengthAdjustment, int initialBytesToStrip, boolean failFast) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength,
                lengthAdjustment, initialBytesToStrip, failFast);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        Object object = null;
        byte type = in.readByte();
        int length = in.readInt();
        ByteBuf buf = in.readBytes(length);
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String requestMessage = new String(req, "UTF-8");
        switch (type) {
            case MessageConstant.GET_POINT_LAST_DATA:
                object = this.gson.fromJson(requestMessage, QueryLastDataList.class);
                break;
            case MessageConstant.GET_POINT_HIS_DATA:
                object = this.gson.fromJson(requestMessage, QueryHistoryDataList.class);
                break;
        }
        logger.info("服务端接收到的信息:{}", object);
        return object;
    }
}
